package cn.xinfei.xdecision.common.service.component.dependency.impl;

import cn.xinfei.xdecision.common.model.component.dependency.EngineNodeComponentRel;
import cn.xinfei.xdecision.common.model.enginex.po.EngineNode;
import cn.xinfei.xdecision.common.service.component.dependency.AbstractDependency;
import cn.xinfei.xdecision.common.service.component.dependency.Dependency;
import cn.xinfei.xdecision.common.utils.enums.enginex.NodeTypeEnum;
import cn.xinfei.xdecision.common.utils.exception.ApiException;
import cn.xinfei.xdecision.common.utils.exception.enums.ErrorCodeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 决策树、决策表、评分卡、复杂规则集、脚本规则集的nodeJson格式是一样的
 */
@Dependency({NodeTypeEnum.DECISION_TREE, NodeTypeEnum.DECISION_TABLES, NodeTypeEnum.SCORECARD, NodeTypeEnum.RULE_BASE})
@Component
public class DecisionTableTreeScorecardDependency extends AbstractDependency {

    @Override
    protected List<EngineNodeComponentRel> initData(final String nodeJson, final EngineNode engineNode) {
        JSONObject jo = JSON.parseObject(nodeJson);
        if (Objects.isNull(jo)) {
            return new ArrayList<>();
        }
        JSONArray componentList = jo.getJSONArray("componentList");
        if (CollectionUtils.isEmpty(componentList)) {
            throw new ApiException(ErrorCodeEnum.NODE_JSON_ERROR);
        }
        return componentList.stream().map(x -> {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(x));
            return initData(engineNode)
                    .setComponentCode(jsonObject.getString("code"))
                    .setComponentVersionNo(jsonObject.getLong("versionNo"));
        }).collect(Collectors.toList());
    }
}
